<script setup lang="ts">
  import { ref, defineProps, reactive, defineExpose } from "vue"
  import { createMessage } from '@/Public-UIlibrary/pb-message/method'
  import { useRouter } from 'vue-router'
  import { getDishTypeTree, getCanteenDishPage, getRecipePlanUpdate } from '@/api/Recipe.ts'
  import { createMsgBox } from "@/Public-UIlibrary/pb-message-box/method.ts"
  let emits = defineEmits('onConfirmModal')
  const router = useRouter()
  const initialPages = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
  }
  const initialform = {
    dishName: '',
    dishTypeCode: '',
    materialCategoryAttributeId: ''
  }
  const tableloading = ref(false)
  const searchForm = ref({ ...initialform })
  const pages = ref({
    ...initialPages
  })
  const showType = ref('添加')
  let loading = ref(false)
  const showDishColumn = computed(() => {
    if (showType.value == '替换') {
      return dishColumn.slice(0, -1)
    } else return dishColumn
  })
  const dishColumn = [
    {
      key: "dishName",

      name: "菜品名称",
    },
    {
      key: "dishTypeName",
      name: "菜品分类",

    },
    {
      key: "skill",
      name: "技法",
    },
    {
      key: "taste",
      name: "味型",
    }, {
      key: "dishRoi",
      name: "原料分类",
    },
    {
      key: "dishRoi",
      name: "售价",
    },
    {
      key: "dishRoi",
      name: "成本",
    },
    {
      key: "dishRoi",
      name: "投产比",
    },
    {
      key: "dishRoi",
      name: "供餐模式",
    },
    {
      slot: 'dishSellPrice',
      name: '份数',
      width: 150,
      fixed: 'right'
    }
  ]
  const dishTypeList = ref([])
  const dishList = ref([])
  let dishCopies = ''
  const replaceDish = ref({})
  let addMealShow = ref(false)
  let addMeal = {}
  const onShow = (type, item, i) => {
    if (i) {
      replaceDish.value = i
      dishCopies = i.dishCopies
      searchForm.value.dishTypeCode = i.dishTypeCode
      getDishTypeTreeApi()
      getCanteenDishPageApi()
    }
    addMealShow.value = true
    showType.value = type
    addMeal = item
  }
  const onInit = () => {
    getDishTypeTreeApi()
    getCanteenDishPageApi()
  }
  const onConfirmFn = () => {
  }

  // 点击树装
  const treeNodeClick = (item) => {
    searchForm.value.dishTypeCode = item.curNode.dishTypeCode
    getCanteenDishPageApi()

  }
  // 分页器修改
  const onPagesChange = () => {
    getCanteenDishPageApi()

  }
  // 遍历数据
  function filterMenu(list) {
    let menuList = list
    menuList.forEach(it => {
      if (it.dishTypeCode != searchForm.value.dishTypeCode) {
        it.disabled = true
      }
      if (it.children) {
        it.children = filterMenu(it.children)
      }
    });

    return menuList
  }
  // 关闭表单重置
  const cancelFn = () => {
    pages.value = initialPages
    getCanteenDishPageApi()
  }
  // 获取菜肴分类列表
  const getDishTypeTreeApi = async () => {
    let res = await getDishTypeTree({ type: 'weight' })
    if (res.code == 2000) {
      if (showType == '替换') {
        res.data.forEach(item => {
        });
      }
      dishTypeList.value = filterMenu(res.data)
      console.log(dishTypeList.value);

    }
  }
  // 确定份数
  const onBlur = (row) => {
    if (row.dishCopies) {
      let params = JSON.parse(JSON.stringify(addMeal))
      let obj = { recipePlanDetailId: null }
      obj['dishCode'] = row.dishCode
      obj['dishCopies'] = row.dishCopies
      let targetIndex = params.dishList.findIndex(item => item.dishCode === row.dishCode);
      console.log(targetIndex);

      if (targetIndex != -1) {
        params.dishList[targetIndex] = obj
      } else {
        params.dishList.push(obj)
      }
      getRecipePlanUpdateApi(params)
    }
  }

  // 点击替换
  const cellClick = (row) => {
    if (showType.value == '替换') {
      row.dishCopies = dishCopies
      let params = JSON.parse(JSON.stringify(addMeal))
      console.log(params.dishList, replaceDish.value);
      let targetIndex = params.dishList.findIndex(item => item.dishCode === replaceDish.value.dishCode);
      params.dishList[targetIndex] = row
      // params.dishList.push(row)
      getRecipePlanUpdateApi(params)
    }
  }
  // 获取菜谱分类列表
  const getCanteenDishPageApi = async () => {
    tableloading.value = true
    let { total, ...arg } = pages.value
    let res = await getCanteenDishPage({
      ...arg,
      ...searchForm.value,
    })
    tableloading.value = false
    if (res.code == 2000) {
      dishList.value = res.data.records
      pages.value.total = res.data.total
    }
  }
  // 编辑食谱
  const getRecipePlanUpdateApi = async (params) => {
    loading.value = true
    let res = await getRecipePlanUpdate(params)
    loading.value = false
    if (res.code == 2000) {
      if (res.data.warnList) {
        createMsgBox(
          '根据当前食增设定参数，无法满足选菜规则，请确认调整规则或者手动调整菜品',
          { cancelText: '调整参数', showTitleIcon: true, confirmText: '手动调整', title: '警告通知', titleType: 'warning', Width: 500, connectList: res.data.warnList, showTitleIcon: true, showIcon: false }).then(res => {
            if (!res) {
              router.push({ path: '/recipeSetting' })
            }
          })
      }
      else {
        createMessage({
          message: `${showType.value}成功`
        })
      }
      emits('onConfirmModal')
      addMealShow.value = false
      cancelFn()
    } else if (res.code == 5002) {
      console.log(res);
      createMsgBox(
        res.msg,
        { cancelText: '调整参数', showTitleIcon: true, confirmText: '手动调整', title: '错误通知', Width: 500, connectList: res.data, showTitleIcon: true, showIcon: false }).then(res => {
          if (!res) {
            router.push({ path: '/recipeSetting' })
          }
        })
    } else {
      getCanteenDishPageApi()
    }
  }

  defineExpose({ onShow })
  onMounted(() => {
    onInit()
  })
</script>

<template>
  <pb-popup v-model="addMealShow" :title="`${showType}菜谱`" Width="1173" :showFoot="false" @confirmFn="onConfirmFn"
    @cancelFn="cancelFn" :loading="loading">
    <div style="height: 650px; padding:  0 16px 16px 16px" class="flex">
      <ContentLeftTree :currentKey="replaceDish.dishTypeName" :treeData="dishTypeList" label="dishTypeName"
        @nodeClick="treeNodeClick">
      </ContentLeftTree>
      <pb-card width="84%" padding="0 16px 0px 16px">
        <div class="flex items-center" style="margin-bottom: 10px;">
          菜品名称:
          <pb-input class="ml-3" v-model="searchForm.dishName" @keyup.enter="getCanteenDishPageApi"
            @blur="getCanteenDishPageApi"></pb-input>
        </div>
        <pb-table :loading="tableloading" :tableData="dishList" style="border-radius: 4px" @cellClick="cellClick"
          :bottomElement="['pb-page',]" height="540px" :column="showDishColumn">
          <template #dishSellPrice="{ row }">
            <div class="flex items-center">
              <pb-input v-model="row.dishCopies" @blur="onBlur(row)" width="100px" height="30px"></pb-input>
            </div>
          </template>
        </pb-table>
        <pb-pagination v-model:currentPage="pages.currentPage" v-model:pageSize="pages.pageSize"
          @onChange="onPagesChange" :total="pages.total"></pb-pagination>

      </pb-card>
      <div class="total"></div>
    </div>

  </pb-popup>
</template>

<style lang="scss" scoped>
  .total {
    height: 200px;
    background-color: var();
  }

  .emty {
    height: 40px;
  }
</style>